//
// Created by ltp on 22-6-22.
//

#include "gui.h"

GUI gui;

void GUI::init(int w, int h) {
    if (win != nullptr) {
        return;
    }
//    SDL_Delay(5000);
    width = w;
    height = h;
    win = SDL_CreateWindow("Media Player",
                           SDL_WINDOWPOS_UNDEFINED,
                           SDL_WINDOWPOS_UNDEFINED,
                           width, height,
                           SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
    if (!win) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to create window by SDL");
        exit(1);
    }

    renderer = SDL_CreateRenderer(win, -1, 0);
    if (!renderer) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to create Renderer by SDL");
        exit(1);
    }

    texture = SDL_CreateTexture(renderer,
                                SDL_PIXELFORMAT_IYUV,
                                SDL_TEXTUREACCESS_STREAMING,
                                width,
                                height);
//    SDL_Delay(5000);
    SDL_Log("CreateWindow...");
}

void GUI::render(const SDL_Rect *rect,
                 const Uint8 *Yplane, int Ypitch,
                 const Uint8 *Uplane, int Upitch,
                 const Uint8 *Vplane, int Vpitch) {

}

void GUI::update(Stream *s) {
    this->init((int) s->width + 50, (int) s->height);
    SDL_UpdateYUVTexture(texture, nullptr,
                         s->data_y, s->size_y,
                         s->data_u, s->size_u,
                         s->data_v, s->size_v
    );

    SDL_Rect rect;
    rect.x = 0;
    rect.y = 0;
    rect.w = width;
    rect.h = height;

    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, texture, nullptr, &rect);
    SDL_RenderPresent(renderer);

    SDL_Event windowEvent;
    if (SDL_PollEvent(&windowEvent)) {
        if (SDL_QUIT == windowEvent.type) {
            exit(2);
        }
    }
}
